using System;
using System.ComponentModel;
using System.Globalization;
using PickGold.Charting.ChartTypes;

namespace PickGold.Charting.Design
{
	internal class SeriesCollectionEditor : ChartCollectionEditor
	{
		public SeriesCollectionEditor()
			: base(typeof(SeriesCollection))
		{
		}

		protected override object CreateInstance(Type itemType)
		{
			if ((base.Context != null) && (base.Context.Instance != null))
			{
				var chartReference = ChartCollectionEditor.GetChartReference(base.Context.Instance) as Chart;
				return CreateNewSeries(chartReference, string.Empty);
			}
			return base.CreateInstance(itemType);
		}

		internal static Series CreateNewSeries(Chart control, string suggestedChartArea)
		{
			int num = control.Series.Count + 1;
			string name = "Series" + num.ToString(CultureInfo.InvariantCulture);
			bool flag = true;
			while (flag)
			{
				flag = false;
				foreach (Series series in control.Series)
				{
					if (series.Name == name)
					{
						flag = true;
					}
				}
				if (flag)
				{
					num++;
					name = "Series" + num.ToString(CultureInfo.InvariantCulture);
				}
			}
			Series series2 = new Series(name);
			if (control.ChartAreas.Count > 0)
			{
				bool flag2 = false;
				if (!string.IsNullOrEmpty(suggestedChartArea) && (control.ChartAreas.IndexOf(suggestedChartArea) != -1))
				{
					series2.ChartArea = suggestedChartArea;
					flag2 = true;
				}
				else
				{
					foreach (ChartArea area in control.ChartAreas)
					{
						if (area.Name == series2.ChartArea)
						{
							flag2 = true;
							break;
						}
					}
				}
				if (!flag2)
				{
					series2.ChartArea = control.ChartAreas[0].Name;
				}
				if (control.ChartAreas[series2.ChartArea].chartAreaIsCurcular)
				{
					series2.ChartTypeName = "Radar";
					IChartType circularChartType = control.ChartAreas[series2.ChartArea].GetCircularChartType() as IChartType;
					if ((circularChartType != null) && (string.Compare(circularChartType.Name, "Polar", StringComparison.OrdinalIgnoreCase) == 0))
					{
						series2.ChartTypeName = "Polar";
					}
				}
			}
			return series2;
		}

		public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
		{
			if (((context != null) && (context.Instance != null)) && (context.Instance is Chart))
			{
				Chart.ControlCurrentContext = context;
			}
			return base.EditValue(context, provider, value);
		}
	}
}

